const ejs = require("ejs");
const rootPaht = require("../../root");
const path = require("path");
const fs = require("fs");
function compileEJS(absPath, data, options = {}) {
	return new Promise((resolve, reject) => {
		const filePaht = path.resolve(rootPaht, absPath);
		ejs.renderFile(filePaht, data, options, function (err, str) {
			if (err) {
				reject(err);
			}
			resolve(str);
			// str => Rendered HTML string
		});
	});
}

function createDir(dirPaht) {
	const pathList = dirPaht.split(path.sep);
	let currenPath = "";
	for (let dir of pathList) {
		currenPath = path.join(currenPath, dir);
		if (fs.existsSync(path.resolve(currenPath))) {
			continue;
		} else {
			//创建目录
			fs.mkdirSync(path.resolve(currenPath));
		}
	}
	//
}
function writeEJS(filePath, filename, EJS, flag = true) {
	let basePath = filePath;
	if (flag) {
		// 是否给文件创建同名的文件夹
		basePath = path.join(filePath, path.parse(filename).name);
	}
	// 创建目录
	createDir(basePath);
	// 写入文件
	return new Promise((resolve, reject) => {
		fs.writeFile(path.join(basePath, filename), EJS, (err, res) => {
			if (err) {
				reject(err);
			} else resolve(res);
		});
	});
}

module.exports = {
	compileEJS,
	writeEJS,
};
